import { Component, OnInit } from '@angular/core';
import { DataService } from '../../feature.dataservice';
import { TFeatures, TScenario } from 'src/app/pages/types';
import { ScenarioService } from 'src/app/share/service/scenario.service';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { RESPONSE_CODE } from 'src/app/share/const/base.const';
import { FeatureScenarioService } from 'src/app/share/service/feature_scenario.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { BehaviorSubject, Subject, debounceTime, throttleTime } from 'rxjs';

/**
 *添加Feature和Scenario的关联关系
 */
@Component({
  selector: 'app-feature-addscenario',
  templateUrl: './feature-addscenario.component.html',
  styleUrls: ['./feature-addscenario.component.less'],
})
export class FeatureAddscenarioComponent implements OnInit {
  // 当前选中的feature;
  feature: TFeatures = { id: -1, feature: '' };

  constructor(
    private store: DataService,
    private scenarioService: ScenarioService,
    private f_sService: FeatureScenarioService,
    private message: NzMessageService
  ) {}

  // 所有的scenarios
  allScenarios: TScenario[] = [];
  // 表格中呈现的数据
  tableData: any[] = [];

  // 输入值发生改变时触发
  inputValueChange$ = new BehaviorSubject('');

  ngOnInit(): void {
    // 第一, 查询所有的scenarios
    this.queryAllScenarios();
    //当前选中的feature更新
    this.store.currentFeature.subscribe((feature) => {
      this.feature = feature;
    });

    // 对输入的值进行防抖操作
    this.inputValueChange$
      .asObservable()
      .pipe(debounceTime(200))
      .subscribe((value) => {
        // 对防抖后的数据进行筛选
        this.filterScenarioBySearchValue(value);
      });
  }

  queryAllScenarios() {
    this.scenarioService.getScenarios().subscribe((res) => {
      const { code, data } = res as RESPONSE_DATA<TScenario[]>;
      if (code === RESPONSE_CODE.SUCCESS) {
        this.allScenarios = data;
      }
    });
  }

  drawerVisable = false;
  checked = false;
  loading = false;
  // 全选状态
  indeterminate = false;
  listOfData: readonly any[] = [];
  listOfCurrentPageData: readonly any[] = [];
  // 选中的id
  setOfCheckedId = new Set<number>();

  // 点击时
  handleClick() {
    // 第二,  点击按钮时, 根据featureid, 查询下属的scenario, 然后根据查询到的scenario数据更新选中状态
    const sids = this.f_sService
      .getSidsByFid(this.feature.id)
      .subscribe((res) => {
        const { code, data } = res as RESPONSE_DATA;
        if (code == RESPONSE_CODE.SUCCESS) {
          data.map((d: any) => {
            this.setOfCheckedId.add(d.sid);
          });
          this.tableData = this.allScenarios;

          this.refreshCheckedStatus();
        }
        this.drawerVisable = true;
      });
  }

  handleSubmit() {
    // const sids = this.setOfCheckedId.
    const sids = Array.from(this.setOfCheckedId);
    // 把fid和sids传给后端, 保存数据
    this.f_sService.createMany(this.feature.id, sids).subscribe((res) => {
      // console.log('res---', res);
      const { code, msg } = res as RESPONSE_DATA;
      if (code == RESPONSE_CODE.SUCCESS) {
        this.message.success('设定成功');
        this.handleDrawClose();
        // 通知Feature主页面,更新数据
        this.store.featureRefresh.next(true);
      } else {
        this.message.error(msg);
      }
    });
  }

  // 全部被选中
  onAllChecked(checked: boolean): void {
    console.log('所有都被选中');
    this.tableData.forEach(({ id }) => this.updateCheckedSet(id, checked));
    // 更新数据
    this.refreshCheckedStatus();
  }

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  // 个别被选中
  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  // 更新选中状态
  refreshCheckedStatus(): void {
    // 是否所有的都在选中set中
    this.checked = this.tableData.every((item) =>
      this.setOfCheckedId.has(item.id)
    );
    this.indeterminate =
      this.tableData.some((item) => this.setOfCheckedId.has(item.id)) &&
      !this.checked;
    // this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    // this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  handleDrawClose() {
    // 清空选中的scenario
    this.setOfCheckedId.clear();
    this.refreshCheckedStatus();
    this.drawerVisable = false;
  }

  value = '';
  // 输入框的值发生改变时触发
  ngModelChange(value: string) {
    this.inputValueChange$.next(value);
  }

  filterScenarioBySearchValue(value: string) {
    const _data = this.allScenarios.filter((item) => {
      return item.scenario.includes(value);
    });
    this.tableData = _data;
  }
}
